﻿using CommonLib.SerializeOperation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommonLib.NetOperation
{
    public class HttpHelper
    {
        /// <summary>
        /// 下载字符串
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string SendHttpRequest(string url, HttpMethod method, object postData = null)
        {
            switch (method)
            {
                case HttpMethod.GET:
                    return DownloadString(url);
                case HttpMethod.POST:
                    return UploadString(url, postData);
                default:
                    throw new NotImplementedException();
            }
        }

        private static string DownloadString(string url)
        {
            var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

            request.Method = HttpMethod.GET.ToString();
            request.ContentType = "application/x-www-form-urlencoded";

            var response = (System.Net.HttpWebResponse)request.GetResponse();

            string downloadString = null;

            using (var responseStream = response.GetResponseStream())
            using (var streamReader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
            {
                downloadString = streamReader.ReadToEnd();
                streamReader.Close();
            }

            request = null;

            return downloadString;
        }

        private static string UploadString(string url, object postData)
        {
            string json = JsonParser.SerializeToJson(postData);
            byte[] buffer = Encoding.UTF8.GetBytes(json);

            var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

            request.Method = HttpMethod.POST.ToString();
            request.ContentType = "application/x-www-form-urlencoded";

            request.ContentLength = buffer.Length;
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(buffer, 0, buffer.Length);
            }

            var response = (System.Net.HttpWebResponse)request.GetResponse();

            string downloadString = null;

            using (var responseStream = response.GetResponseStream())
            using (var streamReader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
            {
                downloadString = streamReader.ReadToEnd();
                streamReader.Close();
            }

            request = null;

            return downloadString;
        }
    }

    public enum HttpMethod
    {
        GET,
        POST
    }
}
